<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="vjImUBDCK8Rg9G13vkIip_GUsZTtVV6s-XdSk81-jzA" />













  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Kotlin,Annotation," />





  <link rel="alternate" href="/atom.xml" title="旺仔的个人博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.png?v=5.1.2" />






<meta name="description" content="接下来学习Kotlin中的注解(Annotations)和类型别名(Type aliases)。">
<meta name="keywords" content="Kotlin,Annotation">
<meta property="og:type" content="article">
<meta property="og:title" content="Kotlin学习_类型别名（Type aliases）和注解（Annotations）">
<meta property="og:url" content="http://www.jowanxu.top/2017/06/28/Kotlin学习_类型别名和注解/index.html">
<meta property="og:site_name" content="旺仔的个人博客">
<meta property="og:description" content="接下来学习Kotlin中的注解(Annotations)和类型别名(Type aliases)。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-254ac6793f182dc6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-54f905cc527c94de.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-c1e06f17f8c46da2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-62f1a4538029b997.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-2fd3e43820c1496e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/1241355-693fbea53b296dab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2017-11-29T00:20:16.013Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Kotlin学习_类型别名（Type aliases）和注解（Annotations）">
<meta name="twitter:description" content="接下来学习Kotlin中的注解(Annotations)和类型别名(Type aliases)。">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/1241355-254ac6793f182dc6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://www.jowanxu.top/2017/06/28/Kotlin学习_类型别名和注解/"/>





  <title>Kotlin学习_类型别名（Type aliases）和注解（Annotations） | 旺仔的个人博客</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>
    <a href="https://github.com/wangzailfm"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">旺仔的个人博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">叫我旺仔<br/>Android Developer</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.jowanxu.top/2017/06/28/Kotlin学习_类型别名和注解/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jowan">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="旺仔的个人博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Kotlin学习_类型别名（Type aliases）和注解（Annotations）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-28T09:31:59+08:00">
                2017-06-28
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2017-11-29T08:20:16+08:00">
                2017-11-29
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Kotlin/" itemprop="url" rel="index">
                    <span itemprop="name">Kotlin</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"> 文章热度</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>°C
            </span>
          

          
            <br/>
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">文章字数</span>
                
                <span title="文章字数">
                  1,879 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长需</span>
                
                <span title="阅读时长需">
                  8 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://upload-images.jianshu.io/upload_images/1241355-254ac6793f182dc6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="An &quot;Object-oriented&quot; Hello"></p>
<p>接下来学习Kotlin中的注解(Annotations)和类型别名(Type aliases)。</p>
<a id="more"></a>
<h2 id="类型别名-Type-aliases-1-1版本"><a href="#类型别名-Type-aliases-1-1版本" class="headerlink" title="类型别名(Type aliases) 1.1版本"></a>类型别名(Type aliases) 1.1版本</h2><p>类型别名为现有类型提供替代名称。如果类型名称太长，您可以引入不同的较短的名称，并使用新的名称。<br>缩短长泛型类型：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">typealias NodeSet = Set&lt;Network.Node&gt;</div><div class="line"></div><div class="line">typealias FileTable&lt;K&gt; = MutableMap&lt;K, MutableList&lt;File&gt;&gt;</div></pre></td></tr></table></figure></p>
<p>可以为功能类型提供不同的别名：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">typealias MyHandler = (<span class="built_in">Int</span>, String, Any) -&gt; <span class="built_in">Unit</span></div><div class="line"></div><div class="line">typealias Predicate&lt;T&gt; = (T) -&gt; <span class="built_in">Boolean</span></div></pre></td></tr></table></figure></p>
<p>可以为内部和嵌套类创建新名称：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</div><div class="line">    inner <span class="class"><span class="keyword">class</span> <span class="title">Inner</span></span></div><div class="line">&#125;</div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> </span>&#123;</div><div class="line">    inner <span class="class"><span class="keyword">class</span> <span class="title">Inner</span></span></div><div class="line">&#125;</div><div class="line"></div><div class="line">typealias AInner = A.Inner</div><div class="line">typealias BInner = B.Inner</div></pre></td></tr></table></figure></p>
<p>Kotlin中定义的类型别名</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1241355-54f905cc527c94de.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>类型别名不会引入新类型，它们相当于相应的底层类型，在代码中添加了<code>typealias Predicate &lt;T&gt;</code>并使用<code>Predicate&lt;Int&gt;</code>时，Kotlin编译器始终将其扩展为<code>(Int) -&gt; Boolean</code>。<br>因此，只要需要一般功能类型，就可以传递类型的变量，反之亦然：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">typealias Predicate&lt;T&gt; = (T) -&gt; <span class="built_in">Boolean</span> <span class="comment">// 这里可以看出变量的类型是函数类型，参数是`T`，返回值是`Boolean`</span></div><div class="line"></div><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">foo方法的返回值是Boolean，因为p的类型为Predicate&lt;Int&gt;，而Predicate&lt;Int&gt;是(Int) -&gt; Boolean。</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">foo</span><span class="params">(p: <span class="type">Predicate</span>&lt;<span class="type">Int</span>&gt;)</span></span> = p(<span class="number">42</span>)</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">(args: <span class="type">Array</span>&lt;<span class="type">String</span>&gt;)</span></span> &#123;</div><div class="line">    <span class="keyword">val</span> f: (<span class="built_in">Int</span>) -&gt; <span class="built_in">Boolean</span> = &#123; it &gt; <span class="number">0</span> &#125;</div><div class="line">    println(foo(f)) <span class="comment">// prints "true"</span></div><div class="line"></div><div class="line">    <span class="keyword">val</span> p: Predicate&lt;<span class="built_in">Int</span>&gt; = &#123; it &gt; <span class="number">0</span> &#125; <span class="comment">// 这里的Predicate&lt;Int&gt;等同于(Int) -&gt; Boolean</span></div><div class="line">    println(listOf(<span class="number">1</span>, <span class="number">-2</span>).filter(p)) <span class="comment">// prints "[1]"</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h2 id="注解声明-Annotation-Declaration"><a href="#注解声明-Annotation-Declaration" class="headerlink" title="注解声明(Annotation Declaration)"></a>注解声明(Annotation Declaration)</h2><p>与Java一样，Kotlin中也是有注解的，同样是用<code>annotation</code>关键字声明：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Fancy</span></span></div></pre></td></tr></table></figure></p>
<p>Kotlin同样可以通过元注解来自定义注解，在这里介绍下元注解：</p>
<h4 id="Retention注解"><a href="#Retention注解" class="headerlink" title="@Retention注解"></a><code>@Retention</code>注解</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-c1e06f17f8c46da2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>指定该注解是否存储在编译后的Class文件中，以及它在运行时能否通过反射可见，有三个值，默认是<code>AnnotationRetention.RUNTIME</code>，分别为：</p>
<ul>
<li><code>AnnotationRetention.SOURCE</code>：不存储在编译后的Class文件。</li>
<li><code>AnnotationRetention.BINARY</code>：存储在编译后的Class文件，但是反射不可见。</li>
<li><code>AnnotationRetention.RUNTIME</code>：存储在编译后的Class文件，反射可见。</li>
</ul>
<h4 id="Target注解"><a href="#Target注解" class="headerlink" title="@Target注解"></a><code>@Target</code>注解</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-62f1a4538029b997.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>表示该注解可以用于什么地方，类型有</p>
<ul>
<li><code>AnnotationTarget.CLASS</code>：类，接口或对象，注解类也包括在内。</li>
<li><code>AnnotationTarget.ANNOTATION_CLASS</code>：只有注解类。</li>
<li><code>AnnotationTarget.TYPE_PARAMETER</code>：<code>Generic type parameter (unsupported yet)</code>通用类型参数（还不支持）。</li>
<li><code>AnnotationTarget.PROPERTY</code>：属性。</li>
<li><code>AnnotationTarget.FIELD</code>：字段，包括属性的支持字段。</li>
<li><code>AnnotationTarget.LOCAL_VARIABLE</code>：局部变量。</li>
<li><code>AnnotationTarget.VALUE_PARAMETER</code>：函数或构造函数的值参数。</li>
<li><code>AnnotationTarget.CONSTRUCTOR</code>：仅构造函数（主函数或者第二函数）。</li>
<li><code>AnnotationTarget.FUNCTION</code>：方法（不包括构造函数）。</li>
<li><code>AnnotationTarget.PROPERTY_GETTER</code>：只有属性的<code>getter</code>。</li>
<li><code>AnnotationTarget.PROPERTY_SETTER</code>：只有属性的<code>setter</code>。</li>
<li><code>AnnotationTarget.TYPE</code>：类型使用。</li>
<li><code>AnnotationTarget.EXPRESSION</code>：任何表达式。</li>
<li><code>AnnotationTarget.FILE</code>：文件。</li>
<li><code>AnnotationTarget.TYPEALIAS</code>：<code>@SinceKotlin(&quot;1.1&quot;)</code>类型别名，Kotlin1.1已可用。</li>
</ul>
<h4 id="Repeatable注解"><a href="#Repeatable注解" class="headerlink" title="@Repeatable注解"></a><code>@Repeatable</code>注解</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-2fd3e43820c1496e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>表示允许在同一申明类型（类，属性，或方法）的多次使用同一个注解</p>
<h4 id="MustBeDocumented注解"><a href="#MustBeDocumented注解" class="headerlink" title="@MustBeDocumented注解"></a><code>@MustBeDocumented</code>注解</h4><p><img src="http://upload-images.jianshu.io/upload_images/1241355-693fbea53b296dab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>
<p>决定了注解是公共API的一部分，因此应该包含在用于注解的元素的生成文档注解中。</p>
<h3 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h3><p>这里声明一个<code>Fancy</code>注解：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION,</span></div><div class="line"><span class="meta">        AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.EXPRESSION)</span></div><div class="line"><span class="meta">@Retention(AnnotationRetention.SOURCE)</span></div><div class="line"><span class="meta">@MustBeDocumented</span></div><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Fancy</span></span></div></pre></td></tr></table></figure></p>
<p>说明：<code>Fancy</code>注解可用在类，接口、对象、注解类、方法（不包括构造函数）、函数或构造函数的值参数和任何的表达式，不存储在编译后的Class文件，可用于生成文档中。</p>
<h3 id="使用-Usage"><a href="#使用-Usage" class="headerlink" title="使用(Usage)"></a>使用(Usage)</h3><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Fancy</span> <span class="class"><span class="keyword">class</span> <span class="title">Foo</span> </span>&#123; <span class="comment">// 用在类上</span></div><div class="line">    <span class="meta">@Fancy</span> <span class="function"><span class="keyword">fun</span> <span class="title">baz</span><span class="params">(<span class="meta">@Fancy</span> foo: <span class="type">Int</span>)</span></span>: <span class="built_in">Int</span> &#123; <span class="comment">// 用在方法上，用在函数的值参数上</span></div><div class="line">        <span class="keyword">return</span> (<span class="meta">@Fancy</span> <span class="number">1</span>) <span class="comment">// 用在任意表达式上</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>如果需要用到主构造函数上，就需要添加<code>constructor</code>关键字，并且在他之前添加注解：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span> <span class="meta">@Inject</span> <span class="keyword">constructor</span></span>(dependency: MyDependency) &#123;</div><div class="line">       <span class="comment">// ...</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>注解属性访问器：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Foo</span> </span>&#123;</div><div class="line">    <span class="keyword">var</span> x: MyDependency? = <span class="literal">null</span></div><div class="line">        <span class="meta">@Inject</span> <span class="keyword">set</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<h3 id="构造方法-Constructors"><a href="#构造方法-Constructors" class="headerlink" title="构造方法(Constructors)"></a>构造方法(Constructors)</h3><p>带参数构造函数的注解：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Special</span></span>(<span class="keyword">val</span> why: String)</div><div class="line"></div><div class="line"><span class="meta">@Special(<span class="meta-string">"example"</span>)</span> <span class="class"><span class="keyword">class</span> <span class="title">Foo</span> </span>&#123;&#125;</div></pre></td></tr></table></figure></p>
<p>参数类型可以有：</p>
<ul>
<li>类型对应于Java原始类型（<code>Int</code>，<code>Long</code>等）</li>
<li>字符串</li>
<li>类（<code>Foo::class</code>）</li>
<li>枚举</li>
<li>其他注解</li>
<li>以上类型的数组</li>
</ul>
<p><strong>注解参数必须是<code>nullable</code>类型，因为JVM不支持将null作为注解属性的值存储。</strong></p>
<p>如果注解被用作另一个注解的参数，它的名称不以<code>@</code>字符做为前缀：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">ReplaceWith</span></span>(<span class="keyword">val</span> expression: String)</div><div class="line"></div><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Deprecated</span></span>(</div><div class="line">        <span class="keyword">val</span> message: String,</div><div class="line">        <span class="keyword">val</span> replaceWith: ReplaceWith = ReplaceWith(<span class="string">""</span>))</div><div class="line"></div><div class="line"><span class="meta">@Deprecated(<span class="meta-string">"This function is deprecated, use === instead"</span>, </span></div><div class="line"><span class="meta">        ReplaceWith(<span class="meta-string">"this === other"</span>)</span>) <span class="comment">// 这里的ReplaceWith注解呗用作另一个注解的参数，则不需要加@符号</span></div></pre></td></tr></table></figure></p>
<p>如果您需要将类指定为注解的参数，请使用Kotlin类（<code>KClass</code>）。<br>Kotlin编译器将自动将其转换为Java类，以便Java代码能够正常看到注解和参数：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> kotlin.reflect.KClass</div><div class="line"></div><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Ann</span></span>(<span class="keyword">val</span> arg1: KClass&lt;*&gt;, <span class="keyword">val</span> arg2: KClass&lt;<span class="keyword">out</span> Any?&gt;)</div><div class="line"></div><div class="line"><span class="meta">@Ann(String::class, Int::class)</span> <span class="class"><span class="keyword">class</span> <span class="title">MyClass</span></span></div></pre></td></tr></table></figure></p>
<h3 id="Lambda"><a href="#Lambda" class="headerlink" title="Lambda"></a>Lambda</h3><p>注解也可以用在lambda表达式中。<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Suspendable</span></span></div><div class="line"></div><div class="line"><span class="keyword">val</span> f = <span class="meta">@Suspendable</span> &#123; Fiber.sleep(<span class="number">10</span>) &#125;</div></pre></td></tr></table></figure></p>
<h2 id="注解使用目标-Annotation-Use-site-Targets"><a href="#注解使用目标-Annotation-Use-site-Targets" class="headerlink" title="注解使用目标(Annotation Use-site Targets)"></a>注解使用目标(Annotation Use-site Targets)</h2><p>当注解属性或主构造函数参数时，有多个Java元素是从相应的Kotlin元素生成的，因此生成的Java字节码中的多个注解位置，要指定应该如何精确地生成注解，使用以下语法：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Example</span></span>(<span class="meta">@field:Ann</span> <span class="keyword">val</span> foo: String,    <span class="comment">// 标注 Java 字段</span></div><div class="line">              <span class="meta">@get:Ann</span> <span class="keyword">val</span> bar: String,      <span class="comment">// 标注 Java getter</span></div><div class="line">              <span class="meta">@param:Ann</span> <span class="keyword">val</span> quux: String)   <span class="comment">// 标注 Java 构造函数参数</span></div></pre></td></tr></table></figure></p>
<p>可以使用相同的语法来注解整个文件，但必须放在最上面，在包指令之前或在所有导入之前：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@file:JvmName</span>(<span class="string">"Foo"</span>)</div><div class="line"></div><div class="line"><span class="keyword">package</span> org.jetbrains.demo</div></pre></td></tr></table></figure></p>
<p>如果有一个使用目标(Use-site Targets)具有多个注解，可以添加方括号<code>[]</code>，并将所有注解放在括号中：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Example</span> </span>&#123;</div><div class="line">       <span class="meta">@set:</span>[Inject VisibleForTesting]</div><div class="line">       <span class="keyword">var</span> collaborator: Collaborator</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>使用例子：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Ann</span></span>()</div><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Annn</span></span>()</div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Example</span></span>(<span class="meta">@field:</span>[Ann Annn] <span class="keyword">val</span> foo: String) &#123;</div><div class="line">      <span class="meta">@set:</span>[Ann Annn]</div><div class="line">      <span class="keyword">var</span> fsoo: String = <span class="string">""</span></div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>使用目标(Use-site Targets)支持的有：</p>
<ul>
<li><code>file</code></li>
<li><code>property</code>使用此目标的注解对Java不可见</li>
<li><code>field</code></li>
<li><code>get</code> 属性的getter</li>
<li><code>set</code> 属性的setter</li>
<li><code>receiver</code> 扩展函数或属性的接收器参数</li>
<li><code>param</code> 构造函数参数</li>
<li><code>setparam</code> 属性的setter的参数</li>
<li><code>delegate</code> 该字段存储代理属性的代理实例</li>
</ul>
<p>其中，要注解扩展函数的接收器参数，请使用以下语法：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">annotation</span> <span class="class"><span class="keyword">class</span> <span class="title">Fancy</span></span></div><div class="line"><span class="function"><span class="keyword">fun</span> @receiver:Fancy String.<span class="title">myExtension</span><span class="params">()</span></span> &#123; &#125;</div></pre></td></tr></table></figure></p>
<p>如果不指定使用目标(Use-site Targets)，则会根据所使用注解的<code>@Target</code>注解来选择目标。<br>如果有多个适用目标，则使用以下列表中的第一个适用目标：</p>
<ul>
<li><code>param</code></li>
<li><code>property</code></li>
<li><code>field</code></li>
</ul>
<h2 id="Java-Annotations"><a href="#Java-Annotations" class="headerlink" title="Java Annotations"></a>Java Annotations</h2><p>Java注解与Kotlin 100％兼容：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">import</span> org.junit.Test</div><div class="line"><span class="keyword">import</span> org.junit.Assert.*</div><div class="line"><span class="keyword">import</span> org.junit.Rule</div><div class="line"><span class="keyword">import</span> org.junit.rules.*</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Tests</span> </span>&#123;</div><div class="line">      <span class="comment">// apply @Rule annotation to property getter</span></div><div class="line">      <span class="meta">@get:Rule</span> <span class="keyword">val</span> tempFolder = TemporaryFolder()</div><div class="line"></div><div class="line">      <span class="meta">@Test</span> <span class="function"><span class="keyword">fun</span> <span class="title">simple</span><span class="params">()</span></span> &#123;</div><div class="line">             <span class="keyword">val</span> f = tempFolder.newFile()</div><div class="line">             assertEquals(<span class="number">42</span>, getTheAnswer())</div><div class="line">       &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>由于Java中编写的注解的参数顺序并没有定义，因此无法使用常规函数调用语法来传递参数，所以就需要使用命名参数语法：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Java</span></div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Ann &#123;</div><div class="line">      <span class="function"><span class="keyword">int</span> <span class="title">intValue</span><span class="params">()</span></span>;</div><div class="line">      <span class="function">String <span class="title">stringValue</span><span class="params">()</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>在Kotlin中调用，使用命名参数：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Kotlin</span></div><div class="line"><span class="meta">@Ann(intValue = 1, stringValue = <span class="meta-string">"abc"</span>)</span> <span class="class"><span class="keyword">class</span> <span class="title">C</span></span></div></pre></td></tr></table></figure></p>
<p>与Java一样，默认的参数名为<code>value</code>，它的值可以被指定而没有明确的名称：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Java</span></div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> AnnWithValue &#123;</div><div class="line">      <span class="function">String <span class="title">value</span><span class="params">()</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>参数名为默认值的时候，可以直接写值：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Kotlin</span></div><div class="line"><span class="meta">@AnnWithValue(<span class="meta-string">"abc"</span>)</span> <span class="class"><span class="keyword">class</span> <span class="title">C</span></span></div></pre></td></tr></table></figure></p>
<p>如果<code>value</code>的参数类型为数组类型的时候，在Kotlin中必须使用<code>vararg</code>这个参数类型：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Java</span></div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> AnnWithArrayValue &#123;</div><div class="line">      String[] value();</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Kotlin</span></div><div class="line"><span class="meta">@AnnWithArrayValue(<span class="meta-string">"abc"</span>, <span class="meta-string">"foo"</span>, <span class="meta-string">"bar"</span>)</span> <span class="class"><span class="keyword">class</span> <span class="title">C</span></span></div></pre></td></tr></table></figure>
<p>如果参数名部位默认值并且为数组类型的时候：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Java</span></div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> AnnWithArrayMethod &#123;</div><div class="line">      String[] names();</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>在Kotlin中必须使用<code>arrayOf</code>，并且使用命名参数：<br><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Kotlin</span></div><div class="line"><span class="meta">@AnnWithArrayMethod(names = arrayOf(<span class="meta-string">"abc"</span>, <span class="meta-string">"foo"</span>, <span class="meta-string">"bar"</span>)</span>) <span class="class"><span class="keyword">class</span> <span class="title">C</span></span></div></pre></td></tr></table></figure></p>
<p>Java注解的实例的值可以做为Kotlin中的属性：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Java</span></div><div class="line"><span class="keyword">public</span> <span class="meta">@interface</span> Ann &#123;</div><div class="line">      <span class="function"><span class="keyword">int</span> <span class="title">value</span><span class="params">()</span></span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// Kotlin</span></div><div class="line"><span class="function"><span class="keyword">fun</span> <span class="title">foo</span><span class="params">(ann: <span class="type">Ann</span>)</span></span> &#123;</div><div class="line">      <span class="keyword">val</span> i = ann.value</div><div class="line">&#125;</div></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Jowan
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://www.jowanxu.top/2017/06/28/Kotlin学习_类型别名和注解/" title="Kotlin学习_类型别名（Type aliases）和注解（Annotations）">http://www.jowanxu.top/2017/06/28/Kotlin学习_类型别名和注解/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Kotlin/" rel="tag"><i class="fa fa-tag"></i> Kotlin</a>
          
            <a href="/tags/Annotation/" rel="tag"><i class="fa fa-tag"></i> Annotation</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/06/19/Kotlin学习_集合和范围/" rel="next" title="Kotlin学习_集合（Collections）和范围（Ranges）">
                <i class="fa fa-chevron-left"></i> Kotlin学习_集合（Collections）和范围（Ranges）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/07/04/Kotlin学习_解构声明/" rel="prev" title="Kotlin学习_解构声明（Destructuring Declarations）">
                Kotlin学习_解构声明（Destructuring Declarations） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjA1My84NjE3"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.gif"
               alt="Jowan" />
          <p class="site-author-name" itemprop="name">Jowan</p>
           
              <p class="site-description motion-element" itemprop="description">叫我旺仔<br/>Android Developer</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">27</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://plus.google.com/u/0/111824269044709365866" target="_blank" title="Google">
                  
                    
                      Google
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://github.com/wangzailfm" target="_blank" title="GitHub">
                  
                    
                      GitHub
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/809077554" target="_blank" title="微博">
                  
                    
                      微博
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="673173629@qq.com" target="_blank" title="E-Mail">
                  
                    
                      E-Mail
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/u011976726" target="_blank" title="CSDN">
                  
                    
                      CSDN
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/u/5509a21c1623" target="_blank" title="简书">
                  
                    
                      简书
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-block">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wanandroid.com/" title="WanAndroid" target="_blank">WanAndroid</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#类型别名-Type-aliases-1-1版本"><span class="nav-number">1.</span> <span class="nav-text">类型别名(Type aliases) 1.1版本</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注解声明-Annotation-Declaration"><span class="nav-number">2.</span> <span class="nav-text">注解声明(Annotation Declaration)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Retention注解"><span class="nav-number">2.0.1.</span> <span class="nav-text">@Retention注解</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Target注解"><span class="nav-number">2.0.2.</span> <span class="nav-text">@Target注解</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Repeatable注解"><span class="nav-number">2.0.3.</span> <span class="nav-text">@Repeatable注解</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#MustBeDocumented注解"><span class="nav-number">2.0.4.</span> <span class="nav-text">@MustBeDocumented注解</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实例"><span class="nav-number">2.1.</span> <span class="nav-text">实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用-Usage"><span class="nav-number">2.2.</span> <span class="nav-text">使用(Usage)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#构造方法-Constructors"><span class="nav-number">2.3.</span> <span class="nav-text">构造方法(Constructors)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Lambda"><span class="nav-number">2.4.</span> <span class="nav-text">Lambda</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注解使用目标-Annotation-Use-site-Targets"><span class="nav-number">3.</span> <span class="nav-text">注解使用目标(Annotation Use-site Targets)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Java-Annotations"><span class="nav-number">4.</span> <span class="nav-text">Java Annotations</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jowan</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Gemini
  </a>
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
